
import 'dart:math' as Math;

import 'dart:math' as Math;

import 'dart:math' as Math;

import 'dart:math' as Math;

import 'dart:math' as Math;

import 'dart:math' as Math;

import 'dart:math' as Math;
import 'package:flutter/widgets.dart';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher.dart';

class LUMAKeysFilepathsObject extends StatefulWidget {
  final String url;

  LUMAKeysFilepathsObject({required this.url});

  @override
  LUMARunnerRegister createState() => LUMARunnerRegister(url: url);
}

class LUMARunnerRegister extends State<LUMAKeysFilepathsObject> {
  final String url;
  late InAppWebViewController buildJute;
  bool _isErrorPageVisible = false;

  LUMARunnerRegister({required this.url});

  InAppWebViewSettings settings = InAppWebViewSettings(
    useOnDownloadStart: true,
    javaScriptEnabled: true,
    mediaPlaybackRequiresUserGesture: false,
    allowFileAccessFromFileURLs: true,
    allowUniversalAccessFromFileURLs: true,
    allowContentAccess: true,
    allowsAirPlayForMediaPlayback: true,
    allowsInlineMediaPlayback: true,
    iframeAllow: "camera; microphone",
    iframeAllowFullscreen: true,
    cacheMode: CacheMode.LOAD_NO_CACHE,
    overScrollMode: OverScrollMode.NEVER,
  );

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.white,
      statusBarIconBrightness: Brightness.dark,
    ));
    String flutter = utf8.decode(base64.decode(widget.url));

    return WillPopScope(
      onWillPop: () async {
        if (await buildJute.canGoBack()) {
          buildJute.goBack();
          return false;
        } else {
          return true;
        }
      },
      child: Scaffold(
        body: SafeArea(
          child: Column(
            children: [
              Visibility(
                visible: !_isErrorPageVisible,
                child: Expanded(
                  child: InAppWebView(
                    initialUrlRequest: URLRequest(url: WebUri(flutter)),
                    onWebViewCreated: (controller) {
                      buildJute = controller;
                    },
                    shouldOverrideUrlLoading:
                        (controller, navigationAction) async {
                      var url = navigationAction.request.url.toString();

                      if (url.endsWith(".pdf")) {
                        String options = Uri.encodeFull(
                            "https://drive.google.com/viewerng/viewer?embedded=true&url=${url.toString()}");
                        controller.loadUrl(
                            urlRequest: URLRequest(
                                url: WebUri.uri(Uri.parse(options))));
                        return NavigationActionPolicy.CANCEL;
                      }

                      var controllerController = navigationAction.request.url;
                      if (controllerController != null) {
                        if (await _calculateTubeDurationMathKeyboardActivity(
                            controllerController)) {
                          return NavigationActionPolicy.CANCEL;
                        }
                      }

                      return NavigationActionPolicy.ALLOW;
                    },
                    onPermissionRequest: (controller, permissionRequest) async {
                      return PermissionResponse(
                          resources: permissionRequest.resources,
                          action: PermissionResponseAction.GRANT);
                    },
                    onLoadStop: (controller, url) async {
                      setState(() {
                        _isErrorPageVisible = false;
                      });
                    },
                  ),
                ),
              ),
              if (_isErrorPageVisible)
                Expanded(
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(16),
                          child: ColorFiltered(
                            colorFilter: ColorFilter.matrix(<double>[
                              0.7152,
                              0.7152,
                              0.0722,
                              0,
                              0,
                              0.7152,
                              0.7152,
                              0.0722,
                              0,
                              0,
                              0.7152,
                              0.7152,
                              0.0722,
                              0,
                              0,
                              0,
                              0,
                              0,
                              1,
                              0,
                            ]),
                            child: Container(
                              color: Colors.white,
                              child: Image(
                                  width: 120,
                                  height: 120,
                                  image: AssetImage('assets/icon.png')),
                            ),
                          ),
                        ),
                        SizedBox(height: 20),
                        Text(
                          "Unable to connect to the internet",
                          style: TextStyle(fontSize: 20),
                        ),
                        SizedBox(height: 20),
                        ElevatedButton(
                          onPressed: _homeLightGestureAreaView,
                          child: Text("Reload"),
                        ),
                        SizedBox(height: 50),
                      ],
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  void _homeLightGestureAreaView() {
    setState(() {
      _isErrorPageVisible = false;
    });
    buildJute.reload();
  }

  Future<bool> _calculateTubeDurationMathKeyboardActivity(Uri uri) async {
    const request = ['whatsapp', 'mailto', 'tel', 'intent'];

    if (request.contains(uri.scheme)) {
      final String url = uri.toString();

      if (uri.scheme == 'intent') {
        final messages = uri.queryParameters['S.browser_fallback_url'];
        if (messages != null) {
          if (await canLaunchUrl(Uri.parse(url))) {
            await launchUrl(Uri.parse(url));
            return true;
          }
        }
      }

      if (await canLaunchUrl(Uri.parse(url))) {
        await launchUrl(Uri.parse(url));
      }
      return true;
    }

    return false;
  }
}
